package com.ruoyi.common.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.net.Ipv4Util;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.system.SystemUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;

/**
 * NetWorkInfoUtil
 *
 * @author kylewka
 * @since 2025/4/8
 */
@Slf4j
public class NetWorkInfoUtil {

    /**
     * 网速测速时间2s
     */
    private static final int SLEEP_MILLIS = 500;

    /**
     * 获取网络上下行速率，格式{"UP": "123KB/S, "DOWN": "345KB/S"}
     *
     * @author xuyuxiang
     * @date 2022/9/1 23:51
     */
    public static Map<String, String> getNetworkUpRate() {
        Map<String, String> result = new HashMap<>();
        Process pro = null;
        Runtime r = Runtime.getRuntime();
        BufferedReader input = null;
        try {
            boolean isWindows = SystemUtil.getOsInfo().isWindows();
            String command = isWindows ? "netstat -e" : "ifconfig";
            pro = r.exec(command);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            long[] result1 = readInLine(input, isWindows);
            Thread.sleep(SLEEP_MILLIS);
            pro.destroy();
            input.close();
            pro = r.exec(command);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            long[] result2 = readInLine(input, isWindows);
            String upSpeed = FileUtil.readableFileSize(Convert.toLong(NumberUtil
                .div(NumberUtil.sub(result2[0], result1[0]), NumberUtil.div(SLEEP_MILLIS, 1000))));
            String downSpeed = FileUtil.readableFileSize(Convert.toLong(NumberUtil
                .div(NumberUtil.sub(result2[1], result1[1]), NumberUtil.div(SLEEP_MILLIS, 1000))));
            result.put("UP", upSpeed + (upSpeed.endsWith("B") ? "/S" : "B/S"));
            result.put("DOWN", downSpeed + (downSpeed.endsWith("B") ? "/S" : "B/S"));
        } catch (Exception e) {
            log.info(">>> 网络测速失败：", e);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    log.info(">>> 网络测速失败：", e);
                }
            }
            Optional.ofNullable(pro).ifPresent(Process::destroy);
        }
        return result;
    }

    private static long[] readInLine(BufferedReader input, boolean isWindows) {
        long[] arr = new long[2];
        StringTokenizer tokenStat;
        try {
            if (isWindows) {
                // 获取windows环境下的网口上下行速率
                input.readLine();
                input.readLine();
                input.readLine();
                input.readLine();
                tokenStat = new StringTokenizer(input.readLine());
                tokenStat.nextToken();
                arr[0] = Long.parseLong(tokenStat.nextToken());
                arr[1] = Long.parseLong(tokenStat.nextToken());
            } else {
                // 获取linux环境下的网口上下行速率
                long rx = 0, tx = 0;
                String line = null;
                //RX packets:4171603 errors:0 dropped:0 overruns:0 frame:0
                //TX packets:4171603 errors:0 dropped:0 overruns:0 carrier:0
                while ((line = input.readLine()) != null) {
                    if (line.contains("RX packets")) {
                        rx += Long.parseLong(line.substring(line.indexOf("RX packets") + 11, line.indexOf(" ",
                            line.indexOf("RX packets") + 11)));
                    } else if (line.contains("TX packets")) {
                        tx += Long.parseLong(line.substring(line.indexOf("TX packets") + 11, line.indexOf(" ",
                            line.indexOf("TX packets") + 11)));
                    }
                }
                arr[0] = rx;
                arr[1] = tx;
            }
        } catch (Exception e) {
            log.error(">>> 网络测速异常：", e);
        }
        return arr;
    }

    /**
     * 获取项目启动的IP地址
     * 注: 仅限springboot项目
     **/
    public static List<String> getIpv4NetworkInterfaces() throws SocketException {
        List<String> addressList = new ArrayList<>();
        addressList.add(Ipv4Util.LOCAL_IP);
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface networkInterface : Collections.list(interfaces)) {
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                if (!inetAddress.isLoopbackAddress() && inetAddress.isSiteLocalAddress()) {
                    String ipAddress = StrUtil.utf8Str(inetAddress.getHostAddress());
                    addressList.add(ipAddress);
                }
            }
        }
        return addressList;
    }
}
